<?php
namespace Admin\Logic;

use Think\Log;

class UserLogic
{
    /**
     * 检测用户名是否存在
     * @param  [type] $userName [用户名]
     * @return [type]           [description]
     */
    public static function verifyUserName($userName)
    {
        try {
            $field = ['id', 'user_name', 'pass_word', 'is_lock'];
            $data = D('user')->where(['user_name' => $userName])->fetchSql(false)->field($field)->find();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取管理员用户列表
     * @param array $where
     * @return mixed
     */
    public static function getAll(array $where = [])
    {
        try {
            $user = D('User');

            if (empty($where)) {
                $data = $user->order('created_at desc')->select();
            } else {
                $map['created_at'] = ['EGT', date('Y-m-d 0:0:0', strtotime($where['start_time']))];
                $map['created_at'] = ['ELT', date('Y-m-d 23:59:59', strtotime($where['end_time']))];

                if (!empty($where['keywords'])) {
                    //检测字段是邮箱还是用户名
                    $field = filter_var($where['keywords'], FILTER_VALIDATE_EMAIL) ? 'email' : 'user_name';
                    $map[$field] = $where['keywords'];
                }

                $data = $user->where($map)->order('created_at desc')->select();
            }
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 执行添加用户操作
     * @param $param
     * @return array|bool
     */
    public static function create($param)
    {
        try {
            $user = D('User');

            if (!$user->create($param)) { //创建数据对象
                return ['code' => 1, 'msg' => $user->getError()];
            } else {
                $id = $user->add();
                return ['code' => 0, 'msg' => $id];
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 删除单条数据
     * @param $id
     * @return mixed
     */
    public static function delete($id)
    {
        try {
            $data = D('User')->delete($id);
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 批量删除多条数据
     * @param string $ids
     * @return mixed
     */
    public static function deleteAll($ids)
    {
        try {
            $data = D('User')->where(['id' => ['in', $ids]])->delete($ids);
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 更新数据信息操作
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function update($data)
    {
        try {
            $update = D('User')->save($data);
            return $update;
        } catch (\Exception $e) {
            return false;
        }
    }
}